package com.blackhorse.demo.questionAnalyze;


import com.blackhorse.domain.Account;

import java.sql.*;

/**
 * JDBC示例程序中的代码耦合与问题分析
 * 耦合：程序之间的依赖关系
 * 包括：类之间的以来
 * 方法间的以来
 * 解耦:
 * 降低程序间的依赖关系
 * <p>
 * 实际开发中应该做到：编译期不依赖，运行期依赖
 * 1）使用反射创建对象，避免使用new创建对象
 * 2）读取配置文件获取要创建的对象的全限定类名
 */
public class JDBCdemoAndQuestion {
    public static void main(String[] args) {
        try {
            //DriverManager.registerDriver(new com.mysql.jdbc.Driver());//类之间存在依赖
            Class.forName("com.mysql.jdbc.Driver");//1）使用反射解决类以来==依赖
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/spring", "root", "root");
            ps = conn.prepareStatement("select  * from account");
            rs = ps.executeQuery();
            while (rs.next()) {
                int id = rs.getInt(1);
                String name = rs.getString(2);
                float money = rs.getFloat(3);
                Account account = new Account();
                account.setId(id);
                account.setName(name);
                account.setMoney(money);
                System.out.println(account);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
